package com.cn.encrypt.mac;

import com.cn.core.constant.MacConstant;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Set;

/**
 * @Author SHANGGUAN
 **/
@SuppressWarnings("all")
public class Macs {


    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
        printlnMacAlgorithms();
        Mac instance = Macs.getInstance(MacConstant.HMAC_MD5, "salt");

    }

    /**
     * 打印 mac 算法
     */
    public static void printlnMacAlgorithms() {
        Set<String> mac = Security.getAlgorithms(MacConstant.MAC);
        for (String macAlgorithms : mac) {
            System.out.println(macAlgorithms);
        }
    }

    public static Mac getInstance(String algorithm) throws NoSuchAlgorithmException {
        return Mac.getInstance(algorithm);
    }




    public static Mac getInstance(String algorithm, String secret) throws NoSuchAlgorithmException, InvalidKeyException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
        SecretKey secretKey = new SecretKeySpec(secret.getBytes(), algorithm);
        Mac instance = Mac.getInstance(keyGenerator.getAlgorithm());
        instance.init(secretKey);
        return instance;
    }
}
